import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { MissionPage } from '../mission/mission';
import { SignupPage } from '../signup/signup';
import { CreditsPage } from '../credits/credits';
import { ProfilePage } from '../profile/profile';
import { RegisterPage } from '../register/register';
import { SettingPage } from '../setting/setting';
import { LevelPage } from '../level/level';

import { Fan } from '../../model/fans/fan.model';
import { Growup } from '../../model/fans/growup.model';
import { FanService } from '../../providers/fan';

import * as moment from 'moment';

// declare var wx: any;

@Component({
	selector: 'page-home',
	templateUrl: 'home.html',
	providers: [FanService]
})
export class HomePage {

	missionPage: any;
	signupPage: any;
	creditsPage: any;
	registerPage: any;
	profilePage: any;
	settingPage: any;
	levelPage: any;

	month: string;
	day: string;

	// 粉丝数据
	fan: Fan;
	growup: Growup;
	integralParam: any;
	levelParam: any;

	constructor(
		private navCtrl: NavController,
		private alertCtrl: AlertController,
		private storage: Storage,
		private fanService: FanService
	) {
		this.missionPage = MissionPage;
		this.signupPage = SignupPage;
		this.creditsPage = CreditsPage;
		this.registerPage = RegisterPage;
		this.profilePage = ProfilePage;
		this.settingPage = SettingPage;
		this.levelPage = LevelPage;

		this.fan = {
			nick_name: '欢迎你',
			head_img: './assets/imgs/default.png',
			sex: '1',
			role: '0',
			member_id: '------------'
		};
		this.month = moment().format('MMM');
		this.day = moment().format('DD');
	};

	ionViewWillEnter() {
		/**
		 * 页面在点击菜单进入时和重新关注时均会发生重定向,在应用内切换页面不会发生重定向
		 * 其中点击菜单进入时用户的openid不会改变，而重新关注时openid发生改变
		 */
		this.storage.get('code').then(v => {
			let code = this.getQueryString('code');
			if (v === null) {
				// 第一次进入(code无缓存)							
				this.initData(code);
			} else if (v === code) {
				// 刷新操作或者切换页面操作(code有缓存但相同)
				this.storage.get('openid').then(oId => {
					this.fanService.getGrowUp(oId).then(res => {
						this.growup = res;
						this.integralParam = {
							'integral': res.integral
						};
						this.levelParam = {
							'level': res.grade,
							'exp': res.experience
						};
					});
					this.storage.get('fan').then(fan => {
						if (fan) {
							this.fan = fan;
						} else {
							this.fanService.getFan(oId).then(res => {
								this.fan = res;
								this.storage.set('fan', res);
							});
						}
					});
				});
			} else {
				// 重新进入或者重新关注(code有缓存但不同)
				this.initData(code);
			};
		});
	};

	// 通过openid获取数据
	initData(code) {
		this.storage.set('code', code);
		this.storage.get('openid').then(v => {
			this.fanService.getOpenId(code).then(res => {
				this.fanService.getGrowUp(res).then(growup => {
					this.growup = growup;
					this.integralParam = {
						'integral': growup.integral
					};
					this.levelParam = {
						'level': growup.grade,
						'exp': growup.experience
					};
				});
				if (v != res) {
					// 缓存的openid不等于获取的 → 重新关注
					this.fanService.getFan(res).then(fan => {
						this.fan = fan;
						this.storage.set('fan', fan);
					});
					this.storage.set('openid', res);
				} else {
					// 缓存的openid等于获取的 → 点击菜单进入
					this.storage.get('fan').then(fan => {
						this.fan = fan;
					})
				};
				this.storage.set('openid', res);
			});
		});
	};

	// 判断是否可以进入签到页面
	canSignup(role) {
		if (role === '1') {
			// 正式会员可进入
			this.navCtrl.push(this.signupPage);
		} else {
			let confirm = this.alertCtrl.create({
				title: '友情提示',
				message: '你好，为享有各种积分优惠，请先完善资料成为正式会员',
				buttons: [
					{
						text: '以后再说',
						handler: () => { }
					},
					{
						text: '去完善资料',
						handler: () => {
							this.navCtrl.push(this.registerPage);
						}
					}
				]
			});
			confirm.present();
		};
	};

	// 判断是否可以进入资料修改页面
	canEditProfile(role) {
		if (role === '1') {
			// 正式会员可进入
			this.navCtrl.push(this.profilePage);
		} else {
			let confirm = this.alertCtrl.create({
				title: '友情提示',
				message: '你好，为享有各种积分优惠，请先完善资料成为正式会员',
				buttons: [
					{
						text: '以后再说',
						handler: () => { }
					},
					{
						text: '去完善资料',
						handler: () => {
							this.navCtrl.push(this.registerPage);
						}
					}
				]
			});
			confirm.present();
		};
	};

	// 设置性别的图标和颜色
	setGenderIcon(sex) { return (sex === '1' ? 'man' : 'female') };
	setGenderColor(sex) { return (sex === '1' ? 'lightblue' : 'teared') };

	// 获取url的search参数
	getQueryString(name) {
		let search = window.location.search;
		let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		let r = search.substr(1).match(reg);
		if (r != null) return r[2];
	};

	// 照相馆
	goToPhoto(){
		this.storage.get('openid').then(v =>{
			window.location.href = "http://pstudio.justbamboo.cn/wechat/entry/"+v
		})	
	};

	// 排队叫号
	goToQueue(){
		this.storage.get('openid').then(v =>{
			window.location.href = "http://m.wio2o.com/index.php?g=Alone&m=QueueWap&a=viewAllProgress&token=kvmuiz1464012971&wecha_id="+v
		})
		
	};
}
